package com.lightsh.sms;

import java.util.ArrayList;
import java.util.List;

import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsConstants {
	
	public static final String TAG = "SmsConstants";
	public static final boolean DEBUG = true;
	
	/**
	 * 所有的短信
	 */ 
	public static final String SMS_URI_ALL = "content://sms/"; 
	/**
	 * 收件箱短信
	 */ 
	public static final String SMS_URI_INBOX = "content://sms/inbox"; 
	/**
	 * 发件箱短信
	 */ 
	public static final String SMS_URI_SEND = "content://sms/sent"; 
	/**
	 * 草稿箱短信
	 */ 
	public static final String SMS_URI_DRAFT = "content://sms/draft"; 
	
	/**
	 * 发件箱
	 */ 
	public static final String SMS_URI_OUTBOX = "content://sms/outbox";
	/**
	 * 发送失败
	 */ 
	public static final String SMS_URI_FAILED = "content://sms/failed";
	/**
	 * 待发送列表
	 */ 
	public static final String SMS_URI_QUEUED = "content://sms/queued";
	
	
	
	public static class SMS{
		public static final String ID = "_id";               					// 一个自增字段，从1开始
		public static final String THREAD_ID = "thread_id"; 		// 序号，同一发信人的id相同
		public static final String  ADDRESS = "address";      		// 发件人手机号码
		public static final String PERSION = "person";        		// 联系人列表里的序号，陌生人为null 
		public static final String  DATE = "date";            				// 发件日期
		public static final String TYPE = "type";     						// ALL = 0; INBOX  = 1; SENT   = 2; DRAFT  = 3; OUTBOX = 4; FAILED = 5; QUEUED = 6; 
		
		private static final String PROTOCOL = "protocol";      	// 协议，分为： 0 SMS_RPOTO, 1 MMS_PROTO  
		private static final String READ = "read";                  		// 是否阅读 0未读， 1已读  
		private static final String STATUS = "status";         			// 状态 -1接收，0 complete, 64 pending, 128 failed 
		private static final String BODY = "body";                     	// 短信内容
		private static final String SERVICE_CENTER = "service_center";     // 短信服务中心号码编号
		private static final String SUBJECT = "subject";            	// 短信的主题
		private static final String REPLY_PATH = "reply_path_present";     // TP-Reply-Path
		private static final String LOCKED = "locked";    
		
		public static final String[] ALL_COLUMN = new String[] { 
			SmsConstants.SMS.ID, 
			SmsConstants.SMS.ADDRESS, 
			SmsConstants.SMS.PERSION, 
    		SmsConstants.SMS.BODY, 
    		SmsConstants.SMS.DATE, 
    		SmsConstants.SMS.TYPE }; 
		
		public static final int SMS_TYPE_ALL = 0;
		public static final int SMS_TYPE_INBOX = 1;
		public static final int SMS_TYPE_SENT = 2;
		public static final int SMS_TYPE_DRAFT = 3;
		public static final int SMS_TYPE_OUTBOX = 4;
		public static final int SMS_TYPE_FAILED = 5;
		public static final int SMS_TYPE_QUEUED = 6;
		
	}
	
	
	public static final List<SmsInfo> getSmsInfo(Context context, Uri uri, String selection){
		ArrayList<SmsInfo> infoList = new ArrayList<SmsInfo>();
        Cursor cusor = context.getContentResolver().query(uri, SMS.ALL_COLUMN, selection, null, SmsConstants.SMS.DATE + " desc");
        try{
        	int idColumn = cusor.getColumnIndex(SmsConstants.SMS.ID);
            int nameColumn = cusor.getColumnIndex(SmsConstants.SMS.PERSION); 
            int phoneNumberColumn = cusor.getColumnIndex(SmsConstants.SMS.ADDRESS); 
            int smsbodyColumn = cusor.getColumnIndex(SmsConstants.SMS.BODY); 
            int dateColumn = cusor.getColumnIndex(SmsConstants.SMS.DATE); 
            int typeColumn = cusor.getColumnIndex(SmsConstants.SMS.TYPE); 
            if (cusor != null && cusor.moveToFirst()) {
            	do{
            		SmsInfo smsinfo = new SmsInfo(
            				cusor.getLong(idColumn), 
            				cusor.getString(smsbodyColumn),
            				cusor.getString(phoneNumberColumn),
            				cusor.getString(dateColumn),
            				cusor.getString(nameColumn),
            				cusor.getInt(typeColumn)); 
                    infoList.add(smsinfo); 
            	}while(cusor.moveToNext());
            } 
        }finally{
        	if(cusor != null){
        		cusor.close();
        	}
        }
        return infoList; 
	}
	
	public static final long getMaxId(Context context){
		Cursor cursor = context.getContentResolver().query(Uri.parse(SmsConstants.SMS_URI_ALL), new String[]{"MAX(" + SMS.ID + ")"}, null, null, null);
		try{
			if(cursor.moveToFirst()){
				return cursor.getLong(0);
			}
		}finally{
			if(cursor != null){
				cursor.close();
			}
		}
		return 0;
	}
	public static final boolean deleteSms(Context context, long id){
		 Uri uri = ContentUris.withAppendedId(Uri.parse(SMS_URI_ALL), id);
	     boolean success = context.getContentResolver().delete(uri, null, null) > 0;
	     Log.i(SmsMonitor.TAG, "delete sms item : " + id + "  result : " + success);
	     return success;
	}
	
	public static final void logSms(String tag, List<SmsInfo> list){
		for(SmsInfo info : list){
			Log.i(tag, info.toString());
		}
	}
	
	/**
	 * 
	 * @param peerPhoneNumber	对方电话号码
	 * @param text								发送的信息
	 * @param sentIntent					发送结果所使用的广播,可以为空
	 */
	public static final void sendSms(String peerPhoneNumber, String text, PendingIntent sentIntent){
		if(peerPhoneNumber == null || peerPhoneNumber.length() == 0 || text == null || text.length() == 0){
			throw new IllegalArgumentException("phone and text cant be empty");
		}
		try{
			SmsManager manager = SmsManager.getDefault();
			ArrayList<String> message = manager.divideMessage(text);
			if(message.size() == 1){
				manager.sendTextMessage(peerPhoneNumber, null, text, sentIntent, null);
			}else{
				ArrayList<PendingIntent> intentList = null;
				if(sentIntent != null){
					intentList = new ArrayList<PendingIntent>();
					for(int i = 0; i < message.size(); ++i){
						intentList.add(sentIntent);
					}
				}
				manager.sendMultipartTextMessage(peerPhoneNumber, null, message, intentList, null);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
